package org.catspaw.cherubim.persistence.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import org.catspaw.cherubim.persistence.transaction.TransactionManager;

public final class TransactionUtils {

	private static TransactionManager	transactionManager	= new HibernateTransactionManager();

	public static Object doInTransaction(HibernateCallback callback)
			throws HibernateException {
		Session session = HibernateSessionFactoryUtils.getCurrentSession();
		boolean binding = session != null;
		if (!binding) {
			session = HibernateSessionFactoryUtils.getSession();
		}
		boolean in = transactionManager.inTransaction();
		try {
			if (!in) {
				transactionManager.beginTransaction();
			}
			Object o = callback.execute(session);
			if (!in) {
				transactionManager.commit();
			}
			return o;
		} catch (RuntimeException e) {
			if (in) {
				transactionManager.rollback();
			}
			throw e;
		} catch (Error e) {
			if (in) {
				transactionManager.rollback();
			}
			throw e;
		} finally {
			if (!binding) {
				HibernateSessionFactoryUtils.closeCurrentSession();
			}
		}
	}
}
